'''
Created on 17-10-2012

@author: LONG HOANG GIANG
'''

from Cheetah.Template import Template
from Model.storymodelv2 import StoryModel
from CrawlerLib import commonlib
import cherrypy


class Category():
   
    database = ''
   
    def __init__(self):
        pass
      
    @cherrypy.expose()
    def index(self, **kwargs):
        if self.database == '': self.database = kwargs.get('database', '')
        if self.database == '': return "Database Not Found"
        storymodel = StoryModel(self.database)
        storymodel.open()
        categories = storymodel.get_all_categories()
        cat = kwargs.get('cid', 0)
        action = '/category/add' if kwargs.get('do', '') != 'edit' else '/category/save?cid={0}'.format(kwargs.get('cid', ''))
        data = {'catName': '', 'catId': '', 'root': ''}
        formsaved = False
        if kwargs.get('do', '') == 'edit':
            t = storymodel.get_category_by_id(cat)
            data['catName'] = t[1]
            data['catId'] = t[0]
            data['root'] = t[2]
            formsaved = True
        data['formsaved'] = formsaved 
        t = Template(file="templates/category.tpl", searchList={'database': self.database, 'data': data, 'categories': categories, 'lastcatid': cat, 'formaction': action}).respond()
        storymodel.close()
        return t
   
    @cherrypy.expose()
    def delete(self, cid, **kwargs):
        storymodel = StoryModel(self.database)
        storymodel.open()
        storymodel.delete_category(cid)
        storymodel.close()
        raise cherrypy.HTTPRedirect("/category")
   
    @cherrypy.expose()
    def add(self, category, **kwargs):
        storymodel = StoryModel(self.database)
        storymodel.open()
        root = kwargs.get('root', 0)
        storymodel.add_category(category, root)
        storymodel.close()
        raise cherrypy.HTTPRedirect("/category/?cat={0}&database={1}".format(root, self.database))
   
    @cherrypy.expose()
    def save(self, cid, category, root, **kwargs):
        storymodel = StoryModel(self.database)
        storymodel.open()
        storymodel.update_category(cid, category, root)
        storymodel.close()
        raise cherrypy.HTTPRedirect("/category?database={0}".format(self.database))
      
